package net.affenkakka.shop;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class AddToBasket
 */
@WebServlet("/AddToBasket")
public class AddToBasket extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		if (session != null && session.getAttribute("customerAuthed") != null && session.getAttribute("customerID") != null && session.getAttribute("customerName") != null)
		{
			HashMap<String, String> newBasket = new HashMap<String, String>();
			@SuppressWarnings("unchecked")
			HashMap<String, String> oldBasket = (HashMap<String, String>) session.getAttribute("customerBasket");
			if (session.getAttribute("customerBasket") != null)
			{
				newBasket = oldBasket;
				if (oldBasket.containsKey(request.getParameter("itemID")))
				{
					int count = Integer.parseInt(oldBasket.get(request.getParameter("itemID")));
					int amount = Integer.parseInt(request.getParameter("amount"));
					newBasket.put(request.getParameter("itemID"), Integer.toString(count + amount));
				} else {
					newBasket.put(request.getParameter("itemID"), request.getParameter("amount"));
				}
			} else {
				newBasket.put(request.getParameter("itemID"), request.getParameter("amount"));
			}
			session.setAttribute("customerBasket", newBasket);
			response.getWriter().println("Items (" + request.getParameter("itemID") + ") has been added!");
			response.setHeader("Refresh", "3; URL=index.jsp");
			
		} else {
			response.getWriter().println("You're not logged in!");
			response.setHeader("Refresh", "3; URL=index.jsp");
		}
	}

}
